package com.example.mall.service;

import com.example.mall.common.core.exception.UnauthorizedException;
import com.example.mall.common.utils.JwtToken;
import com.example.mall.dto.token.TokenGetDTO;
import com.example.mall.dto.user.UserSignUpDTO;
import com.example.mall.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通用-账号密码-认证
 */
@Service
@Transactional
public class PwdAuthenticationService {
    @Autowired
    private UserService userService;

    /**
     * 账号密码登录
     *  - 查询数据库, 下发令牌
     * @param tokenGetDTO
     */
    public String getAccountAdnPassword(TokenGetDTO tokenGetDTO) {
        System.out.println(tokenGetDTO.getAccount());
        User user = userService.selectOneByUsername(tokenGetDTO.getAccount());
        if (user == null) {
            // 账号不存在
            throw new UnauthorizedException(20002);
        }

        return JwtToken.generalToken(user.getId());
    }

    /**
     * 注册新用户并生成令牌
     * @param userSignUpDTO
     * @return token
     */
    public String register(UserSignUpDTO userSignUpDTO) {
        User exists = userService.selectOneByUsername(userSignUpDTO.getAccount());
        if (exists != null) {
            // 账号已存在
            throw new UnauthorizedException(20001);
        }

        // 注册新用户
        // 直接存明文密码 - 加密 TODO
        User user = User.builder()
                .username(userSignUpDTO.getAccount())
                .password(userSignUpDTO.getPassword())
                .build();
        userService.save(user);
        System.out.println("id = " + user.getId());

        // 生成令牌
        return JwtToken.generalToken(user.getId());
    }
}
